package com.plamwind;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;

import com.palmwindActivity.proto.ProtoBuf;
import com.palmwindActivity.proto.ProtoBufUtil;
import com.palmwindActivity.proto.TextUpload;

public class TextUpLoadService {

	public static boolean serve(ProtoBuf[] protoBuf, OutputStream ouputStream)
			throws IOException {
		boolean isSuccess = false;
		if (protoBuf != null) {
			TextUpload.TextUploadReq req = TextUpload.TextUploadReq
					.parseFrom(protoBuf[0].getBufferData());
			String userName = req.getUserName();
			long timeStamp = req.getUploadtime();
			String comment = req.getText();
			isSuccess = writeFile(IServiceConstants.COMMENT_FILE_TEXT, userName, timeStamp,
					comment);
			
			TextUpload.TextUploadResp.Builder respBuilder = TextUpload.TextUploadResp.newBuilder();
			respBuilder.setAction(IServiceConstants.ACTION_UPLOAD_TEXT);
			respBuilder.setResponse(isSuccess? 0 : 1);
			respBuilder.setUserName(userName);
			TextUpload.TextUploadResp resp = respBuilder.build();
			ProtoBuf pb = new ProtoBuf();
			pb.setBufferData(resp.toByteArray());
			pb.setObjType(IServiceConstants.ACTION_UPLOAD_TEXT);
			Vector<ProtoBuf> pbList = new Vector<ProtoBuf>();
			pbList.add(pb);
			byte[] resp_buf = ProtoBufUtil.listToByteArray(pbList);
			ouputStream.write(resp_buf);
			ouputStream.flush();
		}
		return isSuccess;
	}

	protected static boolean writeFile(String fileName, String name, long timeStamp, String comments) {
		File file = new File(fileName);
		boolean isCreateSuccess = false;
		if(!file.exists())
		{
			try {
				isCreateSuccess = file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(!isCreateSuccess)
				return false;
		}
		FileWriter filewriter = null;
		boolean isWriteSuccess = false;
		if(file.canWrite())
		{
		try {
			filewriter = new FileWriter(file, true);
			filewriter.append(name);
			
			filewriter.write("::");
			String timeStampStr = Long.toString(timeStamp);
			filewriter.append(timeStampStr);
			filewriter.append("::");
			filewriter.append(comments);
			filewriter.append("&&&&");
			filewriter.flush();
			isWriteSuccess = true;
			// dispose all the resources after using them.
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				filewriter.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		}
		return isWriteSuccess;
	}
}
